<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI公众号助手</title>
    <link rel="stylesheet" href="/styles.css">
    <style>
        .input-type-toggle {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        .toggle-btn {
            flex: 1;
            padding: 12px 20px;
            background-color: #f5f5f5;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 500;
            color: #666;
            transition: all 0.3s ease;
            text-align: center;
        }
        .toggle-btn:hover {
            background-color: #e8e8e8;
            border-color: #d0d0d0;
        }
        .toggle-btn.active {
            background-color: #4CAF50;
            border-color: #45a049;
            color: white;
        }
        #textInputGroup textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            resize: vertical;
            min-height: 150px;
            font-size: 14px;
            line-height: 1.6;
        }
        #textInputGroup textarea:focus {
            border-color: #4CAF50;
            outline: none;
        }
        #urlInputGroup input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
        }
        #urlInputGroup input:focus {
            border-color: #4CAF50;
            outline: none;
        }
        .article-title {
            width: 100%;
            padding: 15px;
            margin-bottom: 20px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            color: #333;
            background-color: #f9f9f9;
        }
        .article-title:focus {
            border-color: #4CAF50;
            outline: none;
        }
        .article-title .placeholder-text {
            color: #999;
            font-weight: normal;
        }
        .cover-image-container {
            position: relative;
            width: 100%;
            height: 199px;
            margin-bottom: 30px;
            border-radius: 16px;
            overflow: hidden;
            background-color: #f8f9fa;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
        }
        .cover-image-container:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 25px rgba(0, 0, 0, 0.12);
        }
        .cover-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: all 0.5s ease;
        }
        .cover-image-container:hover .cover-image {
            transform: scale(1.02);
        }
        .cover-image-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.4));
            display: flex;
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: all 0.3s ease;
            backdrop-filter: blur(2px);
        }
        .cover-image-container:hover .cover-image-overlay {
            opacity: 1;
        }
        .cover-btn {
            padding: 12px 24px;
            background-color: rgba(255, 255, 255, 0.9);
            color: #333;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .cover-btn:hover {
            background-color: #fff;
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
        }
        .cover-btn::before {
            content: "🖼️";
            font-size: 16px;
        }
        .help-btn {
            margin-right: 16px;
            padding: 8px 18px;
            background-color: #fff;
            color: #1E90FF;
            border: 1.5px solid #1E90FF;
            border-radius: 6px;
            font-size: 15px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            text-decoration: none;
            display: inline-block;
        }
        .help-btn:hover {
            background-color: #1E90FF;
            color: #fff;
        }
        .main-content {
            display: flex;
            flex-direction: column;
            gap: 20px; /* Add some gap between sections */
        }
        .input-section, .output-section {
            background-color: #fff;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.07);
        }

        @media (min-width: 1024px) {
            .main-content {
                flex-direction: row;
                align-items: flex-start; /* Align items to the top */
            }
            .input-section {
                flex: 1;
                max-width: 500px; /* Optional: constrain input section width */
                margin-right: 20px; /* Add margin for spacing */
            }
            .output-section {
                flex: 2; /* Output section can take more space */
            }
        }

        /* New media query for navbar and header adjustments on smaller screens */
        @media (max-width: 768px) {
            .nav-bar {
                flex-direction: column;
                align-items: center;
                padding-bottom: 10px; /* Space below the navbar items before subtitle */
            }

            .logo {
                margin-bottom: 10px; /* Space between logo and the nav-right block */
            }

            .nav-right {
                display: flex;
                flex-direction: row; /* Changed from column to row */
                flex-wrap: wrap; /* Allow items to wrap to the next line */
                justify-content: center; /* Center items horizontally */
                align-items: center;
                gap: 10px; /* Spacing between items */
            }

            #userInfo {
                display: flex; /* Ensure it's flex for proper alignment */
                flex-direction: row; /* Change from column to row */
                align-items: center; /* Vertically align items in the row */
                gap: 8px; /* Spacing for settings, username, logout */
            }

            .header .subtitle {
                text-align: center;
                padding-left: 15px; /* Add some padding to prevent text touching screen edges */
                padding-right: 15px;
            }
        }

        /* Styles for action buttons in the output section */
        .action-btn {
            display: inline-flex;   /* Align icon and text in a row */
            align-items: center;    /* Vertically center icon and text */
            gap: 8px;               /* Space between icon and text, adjust as needed */
            white-space: nowrap;    /* Prevent text from wrapping to a new line */
            /* Add other base styles for .action-btn if they are not in styles.css */
            /* For example, padding, background-color, color, border, border-radius, cursor */
            /* padding: 10px 15px; */
            /* font-size: 14px; */
        }

        /* Optional: if icons need specific alignment or size adjustments */
        /* .action-btn i {
        /*    font-size: 1.1em; /* Example */
        /* } */
        .user-count {
            font-size: 12px;
            color: #666;
            background-color: #f5f5f5;
            padding: 2px 8px;
            border-radius: 12px;
            margin: 0 8px;
        }
        .activate-btn {
            margin-left: 16px;
            padding: 8px 18px;
            background-color: #ff6b6b;
            color: #fff;
            border: none;
            border-radius: 6px;
            font-size: 15px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            text-decoration: none;
            display: inline-block;
        }
        .activate-btn:hover {
            background-color: #ff5252;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
        }
        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            position: relative;
            background-color: #fff;
            margin: 10% auto;
            padding: 30px;
            width: 90%;
            max-width: 400px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            text-align: center;
        }

        .close-btn {
            position: absolute;
            right: 20px;
            top: 15px;
            font-size: 24px;
            color: #666;
            cursor: pointer;
            transition: color 0.3s;
        }

        .close-btn:hover {
            color: #333;
        }

        .qr-container {
            margin-top: 20px;
        }

        .qr-code {
            width: 200px;
            height: 200px;
            margin-bottom: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .qr-tip {
            font-size: 16px;
            color: #333;
            margin-bottom: 10px;
            font-weight: 500;
        }

        .qr-desc {
            font-size: 14px;
            color: #666;
            line-height: 1.5;
        }
    </style>
</head>
<body>
    <div class="container">
        <header class="header">
            <nav class="nav-bar">
                <div class="logo">
                    <h1>AI公众号助手</h1>
                </div>
                <div class="nav-right">
                    <span id="userInfo" style="display: none;">
                        <a href="settings" class="settings-btn">设置</a>
                        <span id="username"></span>
                        <span id="userCount" class="user-count"></span>
                        <a href="/user/logout" class="logout-btn">退出</a>
                    </span>
                    <a href="help" class="help-btn" id="helpBtn">帮助文档</a>
                    <a href="login" class="login-btn" id="loginBtn">登录</a>
                    <a href="/activate" class="activate-btn" id="activateBtn">激活永久使用</a>
                </div>
            </nav>
            <p class="subtitle">自动爬取网页内容并生成精美的公众号推文</p>
        </header>

        <main class="main-content">
            <section class="input-section">
                <h2>输入设置</h2>
                <form id="crawlerForm">
                    <div class="form-group">
                        <div class="input-type-toggle">
                            <button type="button" id="urlInputBtn" class="toggle-btn active">URL输入</button>
                            <button type="button" id="textInputBtn" class="toggle-btn">原文输入</button>
                        </div>
                        <div id="urlInputGroup">
                            <label for="url">目标网页URL</label>
                            <input type="url" id="url" name="url" placeholder="请输入要爬取的网页地址" required>
                        </div>
                        <div id="textInputGroup" style="display: none;">
                            <label for="text">文章内容</label>
                            <textarea id="text" name="text" placeholder="请输入文章内容" rows="6"></textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="keywords">关键词（可选）</label>
                        <div class="keywords-input">
                            <input type="text" id="keywords" name="keywords" placeholder="输入关键词">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="style">文章风格</label>
                        <select id="style" name="style">
                            <option value="professional">专业严谨</option>
                            <option value="casual">轻松活泼</option>
                            <option value="story">故事叙述</option>
                        </select>
                    </div>
                    <button type="submit">开始生成</button>
                </form>
                <div class="loading">
                    <p>正在生成中，请稍候...</p>
                </div>
            </section>

            <section class="output-section">
                <h2>生成结果</h2>
                <div class="preview">
                    <div class="cover-image-container">
                        <img id="coverImage" src="/images/logo.png" alt="文章封面" class="cover-image">
                        <div class="cover-image-overlay">
                            <button id="changeCoverBtn" class="cover-btn">更换封面</button>
                        </div>
                    </div>
                    <div id="titleOutput" class="article-title" contenteditable="true">
                        <div class="placeholder-text">文章标题将显示在这里...</div>
                    </div>
                    <div id="output" class="article-content" contenteditable="true">
                        <div class="placeholder-text">生成的推文将显示在这里...</div>
                    </div>
                </div>
                <div class="loading-container" style="display: none;">
                    <div class="loading-spinner"></div>
                    <p class="loading-text">正在生成文章，请稍候...</p>
                </div>
                <div class="article-actions">
                    <button id="editBtn" class="action-btn" style="display: none;">
                        <i class="icon-edit"></i> 编辑内容
                    </button>
                    <button id="saveBtn" class="action-btn" style="display: none;">
                        <i class="icon-save"></i> 保存修改
                    </button>
                    <button id="copyBtn" class="action-btn" style="display: none;">
                        <i class="icon-copy"></i> 复制内容
                    </button>
                    <button id="publishBtn" class="action-btn" style="display: none;">
                        <i class="icon-publish"></i> 立即群发
                    </button>
                </div>
            </section>
        </main>
    </div>

    <!-- 激活弹窗 -->
    <div id="activateModal" class="modal" style="display: none;">
        <div class="modal-content">
            <span class="close-btn">&times;</span>
            <h2>激活永久使用</h2>
            <div class="qr-container">
                <img src="/wechat_qr.jpg" alt="联系方式" class="qr-code">
                <p class="qr-tip">扫描上方二维码，添加客服微信</p>
                <p class="qr-desc">添加客服后，发送您的用户名，即可获取永久授权码</p>
            </div>
        </div>
    </div>

    <script>
        // 页面加载时检查登录状态
        window.addEventListener('load', function() {
            checkLoginStatus();
            setupInputTypeToggle();
            setupCoverImage();
        });

        // 设置封面图片功能
        function setupCoverImage() {
            const changeCoverBtn = document.getElementById('changeCoverBtn');
            const coverImage = document.getElementById('coverImage');
            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.accept = 'image/*';
            fileInput.style.display = 'none';
            document.body.appendChild(fileInput);

            // 设置默认图片
            const defaultImageUrl = '/images/logo.png';
            coverImage.src = defaultImageUrl;

            // 设置默认图片加载失败的处理
            coverImage.onerror = function() {
                this.src = '';
            };

            changeCoverBtn.addEventListener('click', function() {
                fileInput.click();
            });

            fileInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    // 检查文件类型
                    if (!file.type.startsWith('image/')) {
                        alert('请选择图片文件');
                        return;
                    }

                    // 检查文件大小（限制为5MB）
                    if (file.size > 5 * 1024 * 1024) {
                        alert('图片大小不能超过5MB');
                        return;
                    }

                    const reader = new FileReader();
                    reader.onload = function(e) {
                        coverImage.src = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            });
        }

        // 设置输入类型切换功能
        function setupInputTypeToggle() {
            const urlInputBtn = document.getElementById('urlInputBtn');
            const textInputBtn = document.getElementById('textInputBtn');
            const urlInputGroup = document.getElementById('urlInputGroup');
            const textInputGroup = document.getElementById('textInputGroup');
            const urlInput = document.getElementById('url');
            const textInput = document.getElementById('text');

            function setActiveButton(activeBtn, inactiveBtn) {
                activeBtn.classList.add('active');
                inactiveBtn.classList.remove('active');
            }

            urlInputBtn.addEventListener('click', function() {
                urlInputGroup.style.display = 'block';
                textInputGroup.style.display = 'none';
                urlInput.setAttribute('required', '');
                textInput.removeAttribute('required');
                setActiveButton(urlInputBtn, textInputBtn);
            });

            textInputBtn.addEventListener('click', function() {
                urlInputGroup.style.display = 'none';
                textInputGroup.style.display = 'block';
                urlInput.removeAttribute('required');
                textInput.setAttribute('required', '');
                setActiveButton(textInputBtn, urlInputBtn);
            });
        }

        function checkLoginStatus() {
            fetch('/user/info')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 已登录，显示用户信息和设置按钮
                        document.getElementById('loginBtn').style.display = 'none';
                        document.getElementById('userInfo').style.display = 'inline-flex';
                        document.getElementById('username').textContent = data.username;
                        document.getElementById('userCount').textContent = `剩余次数：${data.count}`;
                        // 根据授权码状态显示激活按钮
                        if (!data.hasAuthCode) {
                            document.getElementById('activateBtn').style.display = 'inline-block';
                        } else {
                            document.getElementById('activateBtn').style.display = 'none';
                        }
                    } else {
                        // 未登录，显示登录按钮
                        document.getElementById('loginBtn').style.display = 'inline';
                        document.getElementById('userInfo').style.display = 'none';
                        document.getElementById('activateBtn').style.display = 'none';
                    }
                })
                .catch(error => {
                    console.error('获取用户信息失败:', error);
                });
        }

        document.getElementById('loginBtn').addEventListener('click', function(e) {
            // 直接跳转到登录页面
            window.location.href = 'login';
        });

        document.getElementById('crawlerForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const submitButton = this.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.textContent;
            submitButton.disabled = true;
            submitButton.textContent = '正在生成...';

            // 显示加载动画
            const loadingContainer = document.querySelector('.loading-container');
            const output = document.getElementById('output');
            loadingContainer.style.display = 'flex';
            output.style.display = 'none';
            
            const formData = {
                url: document.getElementById('url').value,
                text: document.getElementById('text').value,
                keywords: document.getElementById('keywords').value,
                style: document.getElementById('style').value
            };
            
            fetch('/articleCreate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(formData)
            })
            .then(response => response.json())
            .then(data => {
                loadingContainer.style.display = 'none';
                output.style.display = 'block';
                
                if (data.success) {
                    // 显示标题
                    const titleOutput = document.getElementById('titleOutput');
                    titleOutput.innerHTML = data.title || '<div class="placeholder-text">文章标题将显示在这里...</div>';
                    // 显示内容
                    output.innerHTML = data.content;
                    // 显示操作按钮
                    document.getElementById('editBtn').style.display = 'inline-block';
                    document.getElementById('copyBtn').style.display = 'inline-block';
                    document.getElementById('publishBtn').style.display = 'inline-block';
                    // 确保保存按钮是隐藏的
                    document.getElementById('saveBtn').style.display = 'none';
                } else {
                    if (data.message === '请先登录') {
                        window.location.href = '/login';
                    } else {
                        alert(data.message || '生成失败，请稍后重试');
                        output.innerHTML = '<div class="placeholder-text">生成的推文将显示在这里...</div>';
                    }
                }
            })
            .catch(error => {
                loadingContainer.style.display = 'none';
                output.style.display = 'block';
                
                console.error('请求失败:', error);
                alert('请求失败，请稍后重试');
                output.innerHTML = '<div class="placeholder-text">生成的推文将显示在这里...</div>';
            })
            .finally(() => {
                submitButton.disabled = false;
                submitButton.textContent = originalButtonText;
            });
        });

        // 格式化文章内容
        function formatArticleContent(content) {
            // 将内容按段落分割
            const paragraphs = content.split('\n\n');
            
            // 构建HTML
            let html = '';
            paragraphs.forEach((paragraph, index) => {
                if (paragraph.trim()) {
                    if (index === 0) {
                        // 第一段作为标题
                        html += `<h3 class="article-title">${paragraph}</h3>`;
                    } else {
                        // 其他段落
                        html += `<p class="article-paragraph">${paragraph}</p>`;
                    }
                }
            });
            
            return html;
        }

        // 复制内容按钮
        document.getElementById('copyBtn').addEventListener('click', function() {
            const content = document.getElementById('output').innerText;
            navigator.clipboard.writeText(content).then(() => {
                alert('内容已复制到剪贴板！');
            }).catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制');
            });
        });

        // 群发按钮
        document.getElementById('publishBtn').addEventListener('click', function() {
            const publishBtn = document.getElementById('publishBtn');
            if (publishBtn.disabled) return; // 防止极端情况下的多次点击
            publishBtn.disabled = true;
            const originalText = publishBtn.innerHTML;
            publishBtn.innerHTML = '群发中...';

            const content = document.getElementById('output').innerText;
            const title = document.getElementById('titleOutput').textContent.trim();
            const coverImage = document.getElementById('coverImage');
            
            if (content === '生成的推文将显示在这里...') {
                alert('请先生成推文内容！');
                publishBtn.disabled = false;
                publishBtn.innerHTML = originalText;
                return;
            }
            
            // 创建FormData对象
            const requestFormData = new FormData();
            // 将text和title作为JSON字符串传入
            const jsonData = {
                text: document.getElementById('output').innerHTML,
                title: title
            };
            requestFormData.append('data', JSON.stringify(jsonData));

            // 获取封面图片
            fetch(coverImage.src)
                .then(res => res.blob())
                .then(blob => {
                    const file = new File([blob], 'cover.jpg', { type: 'image/jpeg' });
                    requestFormData.append('coverImage', file);
                    sendRequest(requestFormData, publishBtn, originalText);
                })
                .catch(error => {
                    console.error('获取封面图片失败:', error);
                    alert('获取封面图片失败，请重试');
                    publishBtn.disabled = false;
                    publishBtn.innerHTML = originalText;
                });
        });

        // 发送请求
        function sendRequest(formData, publishBtn, originalText) {
            fetch('/createDraft', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('草稿创建成功！');
                } else if (data.message && data.message.includes('没有群发接口权限')) {
                    if (confirm('该帐号没有开通群发权限，需要微信认证。文案已存放在草稿箱，立即跳转去群发？')) {
                        window.location.href = 'https://mp.weixin.qq.com';
                    }
                } else {
                    alert(data.message || '创建草稿失败，请稍后重试');
                }
                if (publishBtn) {
                    publishBtn.disabled = false;
                    publishBtn.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('创建草稿失败:', error);
                alert('创建草稿失败，请稍后重试');
                if (publishBtn) {
                    publishBtn.disabled = false;
                    publishBtn.innerHTML = originalText;
                }
            });
        }

        // 编辑按钮点击事件
        document.getElementById('editBtn').addEventListener('click', function() {
            const output = document.getElementById('output');
            output.contentEditable = true;
            output.focus();
            
            // 隐藏编辑按钮，显示保存按钮
            document.getElementById('editBtn').style.display = 'none';
            document.getElementById('saveBtn').style.display = 'inline-block';
            // 编辑时隐藏复制和发布按钮
            document.getElementById('copyBtn').style.display = 'none';
            document.getElementById('publishBtn').style.display = 'none';
            
            // 添加编辑提示
            const editTip = document.createElement('div');
            editTip.className = 'edit-tip';
            editTip.textContent = '正在编辑模式，点击保存按钮保存修改';
            output.parentNode.insertBefore(editTip, output);
        });

        // 保存按钮点击事件
        document.getElementById('saveBtn').addEventListener('click', function() {
            const output = document.getElementById('output');
            output.contentEditable = false;
            
            // 显示编辑按钮，隐藏保存按钮
            document.getElementById('editBtn').style.display = 'inline-block';
            document.getElementById('saveBtn').style.display = 'none';
            // 保存后显示复制和发布按钮
            document.getElementById('copyBtn').style.display = 'inline-block';
            document.getElementById('publishBtn').style.display = 'inline-block';
            
            // 移除编辑提示
            const editTip = document.querySelector('.edit-tip');
            if (editTip) {
                editTip.remove();
            }
            
            // 保存成功提示
            const saveTip = document.createElement('div');
            saveTip.className = 'save-tip';
            saveTip.textContent = '修改已保存';
            output.parentNode.insertBefore(saveTip, output);
            
            // 3秒后移除提示
            setTimeout(() => {
                saveTip.remove();
            }, 3000);
        });

        // 监听内容变化
        document.getElementById('output').addEventListener('input', function() {
            // 可以在这里添加自动保存或其他功能
        });

        // 激活按钮点击事件
        document.getElementById('activateBtn').addEventListener('click', function(e) {
            e.preventDefault();
            document.getElementById('activateModal').style.display = 'block';
        });

        // 关闭按钮点击事件
        document.querySelector('.close-btn').addEventListener('click', function() {
            document.getElementById('activateModal').style.display = 'none';
        });

        // 点击弹窗外部关闭弹窗
        window.addEventListener('click', function(e) {
            const modal = document.getElementById('activateModal');
            if (e.target === modal) {
                modal.style.display = 'none';
            }
        });
    </script>
</body>
</html> 